package <#if isCloudModel>${cloudSysEngName}<#else>${packageName}</#if>.config.mutidatasource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
<#if databasePool == "Druid">
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
<#else>
import org.springframework.boot.jdbc.DataSourceBuilder;
</#if>
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据源配置类
 *
 * @author zrx
 */
@Configuration
public class DynamicDataSourceConfig {

<#list dataSourceModelMap?keys as key>
    @Bean(name = "${key?uncap_first}")
    @ConfigurationProperties(prefix = "spring.datasource.${key}")
    public DataSource ${key?uncap_first}DataSource() {
    <#if databasePool == "Druid">
        return DruidDataSourceBuilder.create().build();
    <#else>
        return DataSourceBuilder.create().build();
    </#if>
    }
</#list>

	@Bean
	@Primary
	public DataSource dynamicDataSource(<#list dataSourceModelMap?keys as key>@Qualifier(value = "${key?uncap_first}") DataSource ${key?uncap_first}<#if key_has_next>,</#if></#list>) {
		DynamicDataSource dynamicDataSource = new DynamicDataSource();
		//设置默认数据源
		dynamicDataSource.setDefaultTargetDataSource(${dataSourceName?uncap_first});
		Map<Object, Object> dataSourceMap = new HashMap<>();
    <#list dataSourceModelMap?keys as key>
        dataSourceMap.put(DataSourceType.${key?upper_case}, ${key?uncap_first});
    </#list>
		dynamicDataSource.setTargetDataSources(dataSourceMap);
		return dynamicDataSource;
	}

	@Bean
	public PlatformTransactionManager txManager(DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}

}
